"use strict";

//设置
var file_max_size = 1024 * 1024 * 1024,//单文件大小限制false\0不限制
	chunkSize = 1024 * 1024 * 2 ,//单个切片大小
	//注意PHP默认上传文件默认最大2MB   若要更改请找到    upload_max_filesize = 2m ;   这行进行更改
	uploadphp = "/admin/aliyunVideo?FileName=1&Title=2&Action=3&FileSize="+chunkSize,//文件上传php
	accept_type = ".mp4,.flv,.avi,.wmv,.mov,.webm,.mpeg4,.ts,.mpg,.rm,.rmvb,.mkv,.m4v",//空\false\0为不限制
	Maximum = 100,//一次最多可上传数目false\0不限制
	accept_re = false ,//false\0为不允许 true\1 允许  \ "md5"用md5认证是否重复（不推荐）
	show_video = 2 ,//false\0为不允许 true\1 允许  \  2表示无法预览的用红字替代  并可以自动逸点击事件
	at_same=2;//最多同时上传数

//BOX
var box = document.querySelector(".fuploadbox"),
	div = "div",span="span",
	app = addelement(div, "fupload-canary-container", 0, 0, 0, "Fupapp"),
	container = addelement(div, "fupload-container"),
	step1 = addelement(div, "fupload-step1-container", 0, 0, 0, "homeDrop"),
	step1_btn = addelement(div, "fupload-btn"),
	step1_btn_btn = addelement(div, "fupload-btn-btn"),
	step1_btn_icon = addelement(div, "fupload-btn-icon"),
	step1_btn_text = addelement(div, "fupload-btn-text", "上传视频"),
	step2_container = addelement(div, "fupload-step2-container", 0, "margin: 0px auto; display: block;"),
	step2_list = addelement(div, "fupload-file-list"),
	step2_list_title = addelement(div, "fupload-file-title"),
	step2_list_title_h1 = addelement("h1", 0, "文件列表"),
	step2_list_title_p = addelement("p", 0, "推荐采用mp4、flv格式"),
	step2_list_wrp = addelement(div, "fupload-file-list-wrp"),
	step2_add_btn = addelement(div, "fupload-add-btn"),
	step2_add_img = addelement("img", "fupload-add-btn-img", 0, 0, "", 0, "icon_add"),
	step2_add_btn_title = addelement(span, "fupload-add-btn-title", "添加视频"),
	step2_add_btn_more = addelement(div, 0, 0, 0, 0, "fupload-add-btn-more"),
	dividing_line = addelement(div, "fupload-dividing-line"),
	submit_button_container = addelement(div, "fupload-submit-button-group-container"),
	submit_btn_add = addelement(span,"fupload-submit-btn-group-add","立即提交"),
	file_input = document.createElement("input");
file_input.multiple = true;
file_input.type = "file";
file_input.name = "uploader";
file_input.style = step2_container.style = "display: none";
file_input.accept = accept_type;


box.append(file_input);

box.appendChild(app);
app.appendChild(container);
container.appendChild(step1);
//最开始的按钮
step1.appendChild(step1_btn);
step1_btn.appendChild(step1_btn_btn);
step1_btn.appendChild(step1_btn_icon);
step1_btn.appendChild(step1_btn_text);
//文件列表
container.appendChild(step2_container);
step2_container.appendChild(step2_list);
step2_list.appendChild(step2_list_title);
step2_list_title.appendChild(step2_list_title_h1);
step2_list_title.appendChild(step2_list_title_p);
step2_list.appendChild(step2_list_wrp);
step2_list.appendChild(step2_add_btn);
step2_add_btn.appendChild(step2_add_img);
step2_add_btn.appendChild(step2_add_btn_title);
step2_add_btn.appendChild(step2_add_btn_more);
step2_list.appendChild(dividing_line);
step2_container.appendChild(dividing_line);

step2_container.appendChild(dividing_line);
//提交按钮
submit_button_container.appendChild(submit_btn_add);
step2_container.appendChild(submit_button_container);

step1_btn.addEventListener("click", ()=> {
	file_input.click();
});
step2_add_btn.addEventListener("click", ()=> {
	file_input.click();
});

file_input.addEventListener("change", ()=> {	
	let length = file_input.files.length,
		files = file_input.files,
		refuse = 0,
		list_length = list.toArray().length;
	for (let i = 0; i < length; i++) {
		//判断是否允许重复
		if(!accept_re ){
			//不允许
			//获取全部文件名
			let names = ()=>{
				let name = [],
					names = Object.keys(FUploaders);
				for(let i=0;i<names.length;i++){
					name.push(FUploaders[names[i]].file.name);
				}
				return name;
			}
			//有相同文件名的
			if(names().indexOf(files[0].name)!=-1){
				console.log( files[i].name + "文件重复选择");
				refuse++;
				continue;
			}
			
		}
		//判断是否限制大小
		if(file_max_size)
			//判断不通过
			if(file_max_size<=files[i].size){
			console.log( files[i].name + "文件大小不符合");
			refuse++;
			continue;
			}
		//判断是否限制格式（去除空格是否为空）     是否为0/false
		if(accept_type.replace(/\s*/g,"") != "" || !accept_type.replace(/\s*/g,"")){
			//获取文件后缀
			let name = "."+files[i].name.split(".")[files[i].name.split(".").length-1],
				accept = accept_type.replace(/\s*/g,"");
			//判断不通过
			if(accept_type.indexOf(name)==-1){
				console.log( files[i].name + "文件格式不符合");
				refuse++;
				continue;
			}
		}
		//判断上限是否开启
		if(!Maximum)
			if(Maximum<[list_length+i-refuse]){
				console.log( "文件数目已达上限");
				refuse++;
				continue;
			}
		
		//判断第一次的添加
		if(!g){
			step1.style = "display: none";
			step2_container.style ="";
		}
		//获取本次ID
		let id = additem(files[i], step2_list_wrp);
		
	}
	
	ps();
});


submit_btn_add.addEventListener("click", ()=> {
	file_input.click();
});

var list = new Sortable(step2_list_wrp, { 
	handle :".fupload-file-list-item-icon" ,
	animation: 150,onEnd:()=>{
	ps();
}
});

window.addEventListener('offline', function(){
	for(let x in nowup){
		FUploaders[nowup[x]].uploading = 0;
		FUploaders[nowup[x]].currentChunk--;
	}
    console.log('网络连接中断！');
})


//排序
function ps()
{
	let lists = list.toArray(),
		s = lists.length;
	for(var i=0;i<s;i++){
		FUploaders[lists[i]].DOM.item_icon_span.innerText = "P"+[i+1];
	}
}



function additem(file, ele) 
{
	var div = "div",
		DOM = {
			item: addelement(div, "fupload-file-list-item"),
			item_icon: addelement(div, "fupload-file-list-item-icon"),
			item_icon_span: addelement(span),
			item_wap: addelement(div, "fupload-file-list-item-wrp"),
			item_staus_wap: addelement(div, "fupload-item-status-wrp"),
			item_title: addelement("p", "fupload-itme-title", "标题"),
			item_staus_op: addelement(div, "fupload-item-status-op"),
			
			item_staus_pause: addelement(span, "fupload-item-status-click", "暂停"),
			item_staus_del: addelement(span, "fupload-item-status-click", "删除"),
			item_staus_percentage: addelement(span, "fupload-item-status-percentage"),
			item_info: addelement(div, "fupload-item-upload-info"),
			item_info_intro: addelement(span, "fupload-status-intro", "等待上传"),
			item_info_speed: addelement(span, "fupload-speed"),
			item_info_time: addelement(span, "fupload-remain-time"),
			item_progress: addelement(div, "fupload-item-upload-progress"),
			item_progress_show: addelement(div, "fupload-item-upload-progress-loading", 0, "width:0%;")
		};
	
	//判断允许预览
	if(show_video){
		if(["video/mp4","video/fiv"].indexOf(file.type)!=-1){
			//如果文件可以播放添加该按钮
			DOM.item_staus_v = addelement(span, "fupload-item-status-click", "预览该文件");
			DOM.item_staus_op.appendChild(DOM.item_staus_v);
			DOM.item_staus_v.addEventListener("click",()=>{
				//预览
				video_alert(window.URL.createObjectURL(FUploaders[DOM.item.dataset.id].file));
			});	
		}else{
			if(show_video==2){
				DOM.item_staus_v = addelement(span, "fupload-item-status-click", "预览该文件" , "color:red;");
				DOM.item_staus_op.appendChild(DOM.item_staus_v);
			}
		}
	}


	ele.appendChild(DOM.item);
	DOM.item.appendChild(DOM.item_icon);
	DOM.item_icon.appendChild(DOM.item_icon_span);
	DOM.item.appendChild(DOM.item_wap);
	DOM.item_wap.appendChild(DOM.item_staus_wap);
	DOM.item_staus_wap.appendChild(DOM.item_title);
	DOM.item_staus_wap.appendChild(DOM.item_staus_op);
	DOM.item_staus_op.appendChild(DOM.item_staus_pause);
	DOM.item_staus_op.appendChild(DOM.item_staus_del);
	DOM.item_staus_op.appendChild(DOM.item_staus_percentage);
	DOM.item_wap.appendChild(DOM.item_info);
	DOM.item_info.appendChild(DOM.item_info_intro);
	DOM.item_info.appendChild(DOM.item_info_speed);
	DOM.item_info.appendChild(DOM.item_info_time);
	DOM.item_wap.appendChild(DOM.item_progress);
	DOM.item_progress.appendChild(DOM.item_progress_show);

	var id = y();
	FUploaders[id] = {};
	FUploaders[id].DOM = DOM;
	FUploaders[id].file = file;
	
	DOM.item.dataset.id = id ;


	DOM.item_title.innerHTML = file.name.substring(0, file.name.lastIndexOf('.'));
	addvideo(DOM.item.dataset.id);
	
	
	//更改文件名称
	DOM.item_title.addEventListener("click",function(){
		//改标题
		var text = this.innerText,
			p=this,
			box = DOM.item_staus_wap,
			title_edit = addelement(div,"fupload-item-title-edit"),
			input_box = addelement(div,"fupload-input-box-container fupload-input-box-active"),
			input = addelement("input");
			input.type="text";
			input.value = this.innerText;
			input.maxlength="80";
			input_box.appendChild(input);
			title_edit.appendChild(input_box);
		this.before(title_edit);
		this.style = "display : none"
		
		input.focus();
		input.addEventListener("change",()=>{
			//保存文字，为空自动恢复默认
			p.innerText=(this.value.replace(/\s/g, '')=="")?text:this.value;
		})
		
		input.addEventListener("blur",()=>{
			//点击空白处自动保存
			p.style=null;
			title_edit.remove();
		})
		
		input.addEventListener("keypress",()=>{
			//回车自动失去焦点
			input.blur();
		})
		

	});
	
	//暂停-继续 按钮事件
	DOM.item_staus_pause.addEventListener("click",()=>{
		//暂停-继续
		switch(FUploaders[id].uploading)
			{
				case 1:
					//暂停
					FUploaders[id].uploading = 0;
					DOM.item_staus_pause.innerHTML = "继续";
					uplist.splice(uplist.indexOf(id),1);
					nowup.splice(nowup.indexOf(id),1);
					upload();
					break;
				case 0:
					//继续
					uplist.push(id);
					FUploaders[id].uploading = 1;
					DOM.item_staus_pause.innerHTML = "暂停";
					DOM.item_info_intro.innerHTML = "等待上传";
					DOM.item_info_speed.innerHTML = "";
					DOM.item_info_time.innerHTML = "";
					upload();
					break;
			}
		
	});
	
	//删除按钮事件
	DOM.item_staus_del.addEventListener("click",()=>{
		var box = DOM.item_staus_op,
			alert_container = addelement(div,"fupload-op-alert-container"),
			alert_title = addelement(div,"fupload-op-alert-title"),
			alert_title_icon = addelement(span,"fupload-op-alert-title-icon"),
			alert_title_content = addelement(span,"fupload-op-alert-title-content","确定要删除这个视频么？"),
			alert_op = addelement(div,"fupload-op-alert-op"),
			alert_op_cancel = addelement(span,"fupload-op-alert-op-cancel","取消"),
			alert_op_confirm = addelement(span,"fupload-op-alert-op-confirm","确定");
		
		
		alert_title.appendChild(alert_title_icon);
		alert_title.appendChild(alert_title_content);
		alert_op.appendChild(alert_op_cancel);
		alert_op.appendChild(alert_op_confirm);
		alert_container.appendChild(alert_title);
		alert_container.appendChild(alert_op);
		box.appendChild(alert_container);
		
		alert_container.addEventListener("click",()=>{
			//取消删除
			alert_container.remove();
		});
		
		alert_op_confirm.addEventListener("click",()=>{
			//确认删除
			FUploaders[id].uploading = 0;
			if(uplist.indexOf(id)!=-1)uplist.splice(uplist.indexOf(id),1);
			if(nowup.indexOf(id)!=-1)nowup.splice(nowup.indexOf(id),1);
			if(upover.indexOf(id)!=-1)upover.splice(upover.indexOf(id),1);
			DOM.item_info_intro.innerHTML = "删除碎片中......";
			DOM.item_info_speed.innerHTML = "";
			let fd = new FormData();
			fd.append("id",id);
			fd.append('act', 'del');
			fd.append('load', FUploaders[id].load);
			fd.append('filename', FUploaders[id].file.name);
			let xhr = new XMLHttpRequest();
			xhr.open('post',uploadphp);
			xhr.send(fd);
			xhr.onreadystatechange = ()=> {
				if (xhr.readyState == 4 && xhr.status == 200 ) {
					DOM.item.remove();
					console.log(id + " 已删除");
					delete FUploaders[id]
					//从文件列表移除
				}
			}
		});
		
		
	});



	return id;
}


g = 0; 
function y()
{
	var e = Math.random().toString(32).substr(2, 5),
		t = Math.floor(Date.now() / 1e3);
	return "FUploader_".concat(g++, "_").concat(e, "_").concat(t)
}

function addelement(ele, css = !1, text = !1, style = !1, src = !1, id = !1, alt = !1) 
{
	var mele = document.createElement(ele);
	if (css) mele.className = css;
	if (text) mele.innerHTML = text;
	if (style) mele.style = style;
	if (src) mele.src = src;
	if (id) mele.id = id;
	return mele;
}